package com.wn.order.service.impl;

import com.wn.order.client.AccountClient;
import com.wn.order.client.StorageClient;
import com.wn.order.entity.Order;
import com.wn.order.mapper.OrderMapper;
import com.wn.order.service.OrderService;
import feign.FeignException;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private  AccountClient accountClient;

    @Autowired
    private  StorageClient storageClient;

    @Autowired
    private  OrderMapper orderMapper;

    // 全局的注解
    @GlobalTransactional
    @Override
    public Long create(Order order) {

        log.info("传递过来的是:{}",order);

        // 创建订单
        orderMapper.insert(order);
        try {
            // 扣用户余额     调用 account-service 服务
            accountClient.deduct(order.getUserId(), order.getMoney());
            // 扣库存         调用 storage-service 服务
            storageClient.deduct(order.getCommodityCode(), order.getCount());

        } catch (FeignException e) {
            log.error("下单失败，原因:{}", e.contentUTF8(), e);
            throw new RuntimeException(e.contentUTF8(), e);
        }
        return order.getId();
    }
}
